package dispatcher;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
/**
 * 
 * @author LocoRocoBattleStein
 *
 */
public class ClientListener implements Runnable{
	private Socket socket;
	private Thread t;
	private BufferedReader reader;
	private BufferedWriter writer;
	private ServerDispatcher sdp;
	
	public ClientListener(Socket socket, ServerDispatcher sdp) {
		this.socket = socket;
		this.sdp = sdp;
		try {
			this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		t = new Thread(this);
		t.start();
	}
	
	public void run() {
		while(true) {
		System.out.println("Listening client");
		try {
			char[] req = new char[100];
			int i=0;
			while ((req[i] = (char)reader.read()) != '\n') {
				System.out.println("New char : "+req[i]);
				i++;
			}
			char[] request = new char[i];
			for(int j = 0; j < i; j++) request[j] = req[j];
			String line = new String(request);
			
			synchronized(sdp) {
				sdp.addRequest(line);
			}
			System.out.println("New line : "+line);
		} catch (Exception e) {
			e.printStackTrace();
		} /*finally {
			try {
				if (reader != null)
					reader.close();
				if (socket != null)
					socket.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}*/
		}
	}
	
	public void sendRequest(String request) {
		try {
			writer.write(request);
			writer.flush();
			System.out.println("UPDATING TOWER CL " + request);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
